<script>
import { login, register } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Lock, Message, Phone } from '@element-plus/icons-vue'

export default {
  name: 'LoginPage',
  components: {
    User,
    Lock,
    Message,
    Phone
  },
  data() {
    // 密码确认验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.userPassword) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }

    return {
      loading: false,
      showRegister: false,
      showForgotPassword: false,
      // 1. 关键修改：登录表单字段名改为 userEmail 和 userPassword（匹配后端）
      loginForm: {
        userEmail: '', // 对应后端登录接口的 userEmail 字段（邮箱登录）
        userPassword: '' // 对应后端登录接口的 userPassword 字段
      },
      registerForm: {
        userName: '',
        userEmail: '',
        userPassword: '',
        confirmPassword: ''
      },
      // 2. 关键修改：登录规则字段同步改为 userEmail 和 userPassword
      loginRules: {
        userEmail: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' } // 新增邮箱格式校验
        ],
        userPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' } // 新增密码长度校验
        ]
      },
      registerRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '用户名长度在2到20个字符', trigger: 'blur' }
        ],
        userEmail: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        userPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
  async handleLogin() {
    try {
      await this.$refs.loginForm.validate()
      this.loading = true

      const loginData = {
        userEmail: this.loginForm.userEmail,
        userPassword: this.loginForm.userPassword
      }

      console.log('发送登录请求数据:', loginData)
      const response = await login(loginData)

      // 关键修改：后端成功码是 0，而非 1，同步修改判断条件
      if (response.code === 0 && response.data) {
        // 构建用户信息（可暂存已知信息，后续通过 /user/userinfo 接口获取完整信息）
        const userInfo = {
          userId: '', // 暂时为空，后续可通过 getUserInfo 接口获取
          userName: 'cps114', // 从后端日志可知用户名，也可后续接口获取
          userEmail: this.loginForm.userEmail,
          userRole: 'user', // 从后端日志可知角色
          userStatus: '0' // 默认正常状态
        }

        // 保存 Token 和用户信息到本地存储
        localStorage.setItem('token', response.data) // 后端 data 字段是 Token
        localStorage.setItem('userInfo', JSON.stringify(userInfo))

        ElMessage.success('登录成功')
        // 跳转到首页
        this.$router.push('/')
      } else {
        // 后端返回错误信息（如密码错误、用户封禁等）
        ElMessage.error(response.message || '登录失败，用户名或密码错误')
      }
    } catch (error) {
      console.error('登录错误详情:', error);
      if (error.message.includes('ERR_CONNECTION_REFUSED')) {
        ElMessageBox.alert(
          '登录失败！无法连接到服务器，请检查后端服务是否启动',
          '连接错误',
          { type: 'error' }
        )
      } else if (error.response) {
        console.error('服务器错误响应:', error.response);
        ElMessage.error('登录失败：' + (error.response.data?.message || '服务器错误'))
      } else {
        ElMessage.error('登录失败：' + (error.message || '未知错误'))
      }
    } finally {
      this.loading = false
    }
  },
    async handleRegister() {
      try {
        await this.$refs.registerForm.validate()

        // 过滤无效字段（confirmPassword 无需传给后端）
        const registerData = {
          userName: this.registerForm.userName,
          userEmail: this.registerForm.userEmail,
          userPassword: this.registerForm.userPassword
        }

        console.log('发送注册请求:', registerData);
        const response = await register(registerData);
        console.log('注册响应:', response);

        // 修复：后端成功码是 0（从登录逻辑可以看出），不是 1
        if (response.code === 0) {
          ElMessage.success(response.message || '注册成功，请登录')
          this.showRegister = false
          // 重置注册表单
          this.registerForm = {
            userName: '',
            userEmail: '',
            userPassword: '',
            confirmPassword: ''
          }
          this.$refs.registerForm.resetFields()
        } else {
          // 修复：使用 response.message 显示错误信息，不是 response.msg
          ElMessage.error(response.message || '注册失败')
        }
      } catch (error) {
        console.error('注册错误详情:', error);
        if (error.message.includes('ERR_CONNECTION_REFUSED')) {
          ElMessageBox.alert(
            '注册失败！无法连接到服务器，请检查后端服务是否启动',
            '连接错误',
            { type: 'error' }
          )
        } else if (error.response) {
          // 服务器返回了错误响应
          console.error('服务器错误响应:', error.response);
          ElMessage.error('注册失败：' + (error.response.data?.message || '服务器错误'))
        } else {
          ElMessage.error('注册失败：' + (error.message || '未知错误'))
        }
      }
    },

    showForgotPasswordDialog() {
      this.showForgotPassword = true
    }
  }
}
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <div class="login-icon">
          <svg width="90" height="90" viewBox="0 0 90 90" fill="none" xmlns="http://www.w3.org/2000/svg">
            <defs>
              <linearGradient id="bookGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
                <stop offset="50%" style="stop-color:#764ba2;stop-opacity:1" />
                <stop offset="100%" style="stop-color:#f093fb;stop-opacity:1" />
              </linearGradient>
              <linearGradient id="pageGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:#ffffff;stop-opacity:0.9" />
                <stop offset="100%" style="stop-color:#f8f9ff;stop-opacity:0.8" />
              </linearGradient>
              <filter id="shadow" x="-50%" y="-50%" width="200%" height="200%">
                <feDropShadow dx="0" dy="4" stdDeviation="8" flood-color="#667eea" flood-opacity="0.3"/>
              </filter>
            </defs>

            <!-- 背景圆形 -->
            <circle cx="45" cy="45" r="42" fill="url(#bookGradient)" filter="url(#shadow)"/>

            <!-- 书本主体 -->
            <rect x="25" y="20" width="40" height="50" rx="3" fill="url(#pageGradient)" stroke="url(#bookGradient)" stroke-width="2"/>

            <!-- 书页 -->
            <rect x="28" y="23" width="34" height="44" rx="2" fill="white" opacity="0.9"/>

            <!-- 文字行 -->
            <rect x="30" y="30" width="20" height="2" rx="1" fill="url(#bookGradient)" opacity="0.7"/>
            <rect x="30" y="35" width="25" height="2" rx="1" fill="url(#bookGradient)" opacity="0.5"/>
            <rect x="30" y="40" width="18" height="2" rx="1" fill="url(#bookGradient)" opacity="0.6"/>
            <rect x="30" y="45" width="22" height="2" rx="1" fill="url(#bookGradient)" opacity="0.4"/>
            <rect x="30" y="50" width="16" height="2" rx="1" fill="url(#bookGradient)" opacity="0.5"/>

            <!-- 装饰性元素 -->
            <circle cx="35" cy="60" r="2" fill="url(#bookGradient)" opacity="0.6"/>
            <circle cx="40" cy="62" r="1.5" fill="url(#bookGradient)" opacity="0.4"/>
            <circle cx="45" cy="60" r="1" fill="url(#bookGradient)" opacity="0.5"/>

            <!-- 高光效果 -->
            <ellipse cx="35" cy="25" rx="8" ry="3" fill="white" opacity="0.3"/>
          </svg>
        </div>
        <h2>图书管理系统</h2>
        <p class="login-subtitle">Library Management System</p>
      </div>

      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @submit.prevent="handleLogin">

        <!-- 5. 关键修改：表单项目 prop 和输入框 v-model 同步改为 userEmail -->
        <el-form-item prop="userEmail">
          <el-input
            v-model="loginForm.userEmail"
            placeholder="请输入邮箱"
            size="large">
            <template #prefix>
              <el-icon class="input-icon">
                <User />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 6. 关键修改：表单项目 prop 和输入框 v-model 同步改为 userPassword -->
        <el-form-item prop="userPassword">
          <el-input
            v-model="loginForm.userPassword"
            type="password"
            placeholder="请输入密码"
            size="large"
            @keyup.enter="handleLogin">
            <template #prefix>
              <el-icon class="input-icon">
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="login-button"
            :loading="loading"
            @click="handleLogin">
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>

        <div class="login-options">
          <el-link type="primary" @click="showRegister = true">注册账号</el-link>
          <el-link type="primary" @click="showForgotPasswordDialog">忘记密码？</el-link>
        </div>
      </el-form>
    </div>

    <!-- 注册对话框 -->
    <el-dialog title="用户注册" v-model="showRegister" width="400px">
      <el-form ref="registerForm" :model="registerForm" :rules="registerRules" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="registerForm.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="registerForm.userEmail" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userPassword">
          <el-input v-model="registerForm.userPassword" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请确认密码"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRegister = false">取消</el-button>
        <el-button type="primary" @click="handleRegister">注册</el-button>
      </template>
    </el-dialog>

    <!-- 忘记密码对话框 -->
    <el-dialog title="忘记密码" v-model="showForgotPassword" width="450px" align-center>
      <div class="forgot-password-content">
        <div class="forgot-password-icon">
          <svg width="80" height="80" viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg">
            <defs>
              <linearGradient id="helpGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
                <stop offset="50%" style="stop-color:#764ba2;stop-opacity:1" />
                <stop offset="100%" style="stop-color:#f093fb;stop-opacity:1" />
              </linearGradient>
            </defs>
            <circle cx="40" cy="40" r="35" fill="url(#helpGradient)" opacity="0.1"/>
            <circle cx="40" cy="40" r="30" fill="url(#helpGradient)" opacity="0.2"/>
            <path d="M40 20C28.95 20 20 28.95 20 40s8.95 20 20 20 20-8.95 20-20S51.05 20 40 20zm0 36c-8.84 0-16-7.16-16-16s7.16-16 16-16 16 7.16 16 16-7.16 16-16 16z" fill="url(#helpGradient)"/>
            <path d="M40 28c-2.21 0-4 1.79-4 4h4v4h-4c0 2.21 1.79 4 4 4s4-1.79 4-4c0-1.1-.45-2.1-1.17-2.83L40 32.83V28z" fill="url(#helpGradient)"/>
            <circle cx="40" cy="52" r="3" fill="url(#helpGradient)"/>
          </svg>
        </div>
        <h3 class="forgot-password-title">需要重置密码？</h3>
        <p class="forgot-password-desc">
          很抱歉，系统暂不支持自助密码重置功能。如果您忘记了密码，请联系系统管理员进行密码重置。
        </p>
        <div class="contact-info">
          <div class="contact-item">
            <el-icon class="contact-icon"><Message /></el-icon>
            <span>邮箱：admin@library.com</span>
          </div>
          <div class="contact-item">
            <el-icon class="contact-icon"><Phone /></el-icon>
            <span>电话：400-123-4567</span>
          </div>
          <div class="contact-item">
            <el-icon class="contact-icon"><User /></el-icon>
            <span>管理员：系统管理员</span>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showForgotPassword = false">关闭</el-button>
          <el-button type="primary" @click="showForgotPassword = false">我知道了</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 样式部分完全不变，保持原样 */
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

/* 添加动态背景装饰 */
.login-container::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 1px, transparent 1px);
  background-size: 50px 50px;
  animation: float 20s infinite linear;
  pointer-events: none;
}

@keyframes float {
  0% { transform: translate(0, 0) rotate(0deg); }
  100% { transform: translate(-50px, -50px) rotate(360deg); }
}

.login-box {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 25px;
  padding: 50px 40px;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
  width: 100%;
  max-width: 420px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  position: relative;
  z-index: 10;
  animation: slideInUp 0.8s ease-out;
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(50px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
  animation: fadeInDown 1s ease-out 0.3s both;
}

.login-icon {
  width: 90px;
  height: 90px;
  margin: 0 auto 20px auto;
  transition: all 0.3s ease;
  cursor: pointer;
}

.login-icon:hover {
  transform: scale(1.05) rotate(5deg);
}

.login-icon svg {
  width: 100%;
  height: 100%;
  filter: drop-shadow(0 10px 30px rgba(102, 126, 234, 0.3));
}

.login-header h2 {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 700;
  letter-spacing: 1px;
}

.login-subtitle {
  color: #8b9dc3;
  font-size: 14px;
  font-weight: 400;
  margin: 0;
  letter-spacing: 0.5px;
  opacity: 0.8;
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-form {
  margin-top: 20px;
  animation: fadeInUp 1s ease-out 0.6s both;
}

.login-button {
  width: 100%;
  height: 55px;
  font-size: 18px;
  font-weight: 600;
  border-radius: 30px;
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
  border: none;
  color: #333;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.login-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #d299c2, #fef9d7);
  transition: left 0.5s ease;
  z-index: -1;
}

.login-button:hover::before {
  left: 0;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 25px rgba(168, 237, 234, 0.4);
  color: #333;
}

.login-button:active {
  transform: translateY(0);
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-options {
  display: flex;
  justify-content: space-between;
  margin-top: 25px;
  animation: fadeInUp 1s ease-out 0.9s both;
}

.el-form-item {
  margin-bottom: 25px;
  animation: fadeInUp 1s ease-out 0.7s both;
}

.el-form-item:nth-child(2) {
  animation-delay: 0.8s;
}

.el-input {
  border-radius: 30px;
  transition: all 0.3s ease;
}

.el-input:hover {
  transform: translateY(-2px);
}

.el-input__wrapper {
  border-radius: 30px;
  height: 55px;
  line-height: 55px;
  border: 2px solid rgba(168, 237, 234, 0.3);
  background: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
}

.el-input__wrapper:hover {
  border-color: #a8edea;
  box-shadow: 0 5px 15px rgba(168, 237, 234, 0.2);
}

.el-input__wrapper.is-focus {
  border-color: #a8edea;
  box-shadow: 0 5px 20px rgba(168, 237, 234, 0.3);
}

.el-link {
  color: #a8edea;
  font-weight: 500;
  transition: all 0.3s ease;
}

.el-link:hover {
  color: #d299c2;
  transform: translateY(-1px);
}

.input-icon {
  background: linear-gradient(135deg, #a8edea, #fed6e3);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transition: all 0.3s ease;
  font-size: 18px;
}

.el-input__wrapper:hover .input-icon {
  background: linear-gradient(135deg, #d299c2, #fef9d7);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transform: scale(1.1);
}

.el-input__wrapper.is-focus .input-icon {
  background: linear-gradient(135deg, #d299c2, #fef9d7);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transform: scale(1.1);
}

.profile-info p {
  margin: 10px 0;
  font-size: 16px;
}

/* 忘记密码对话框样式 */
.forgot-password-content {
  text-align: center;
  padding: 20px 0;
}

.forgot-password-icon {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

.forgot-password-icon svg {
  filter: drop-shadow(0 4px 12px rgba(102, 126, 234, 0.3));
}

.forgot-password-title {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 15px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.forgot-password-desc {
  color: #666;
  line-height: 1.6;
  margin: 0 0 25px 0;
  font-size: 14px;
}

.contact-info {
  background: rgba(102, 126, 234, 0.05);
  border-radius: 12px;
  padding: 20px;
  margin: 20px 0;
  border: 1px solid rgba(102, 126, 234, 0.1);
}

.contact-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin: 12px 0;
  color: #555;
  font-size: 14px;
}

.contact-icon {
  color: #667eea;
  font-size: 16px;
}

.dialog-footer {
  text-align: center;
  padding-top: 10px;
}

.dialog-footer .el-button {
  margin: 0 8px;
}
</style>
